package com.gugu.procedure.controller;


import com.gugu.procedure.bean.*;
import com.gugu.procedure.common.Constant;
import com.gugu.procedure.common.MessageResult;
import com.gugu.procedure.param.ProductionRecordNumberSubmitParam;
import com.gugu.procedure.service.*;
import com.gugu.procedure.util.DateUtil;
import com.gugu.procedure.util.StringUtil;
import com.gugu.procedure.vo.OrderProductionRecordVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = {"工艺流转"})
@RequestMapping("productionRecord")
public class ProductionRecordController extends BaseController {
    @Autowired
    private ProductionRecordService productionRecordService;
    @Autowired
    private InsideOrderService insideOrderService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private ProductionService productionService;
    @Autowired
    private OrderProductionRecordService orderProductionRecordService;


    @GetMapping("open/nextProductionRecord")
    @ApiOperation(value = "查询新品订单的订单的下一个工序")
    public MessageResult queryNextProductionRecord(String orderNo, String number) {
        return MessageResult.getSuccessInstance((Object) productionRecordService.queryProductionRecordByOrderNoAndNumber(orderNo, number));
    }

    @PostMapping("open/submitNew")
    @ApiOperation(value = "新品订单提交工序")
    public MessageResult submitNew(@RequestBody ProductionRecordNumberSubmitParam productionRecordNumberSubmitParam) {
        Staff staff = staffService.findByStaffNumber(productionRecordNumberSubmitParam.getStaffNumber());
        if (staff == null) {
            return MessageResult.error("请重新扫码员工码");
        }
        ProductionRecord productionRecord = new ProductionRecord();
        String orderNo = productionRecordNumberSubmitParam.getOrderNo();
        productionRecord.setCreateTime(DateUtil.getFormatedDateTime());
        productionRecord.setOrderNo(orderNo);
        productionRecord.setStaffId(staff.getId());
        productionRecord.setNgTag("0");
        productionRecord.setStaffName(staff.getName());
        productionRecord.setWorkDoneFlag(Constant.WORK_DONE_FLAG_N);
        productionRecord.setStaffNumber(staff.getNumber());
        OrderItem orderItem = insideOrderService.queryOrderItemByOrderNoAndNumber(orderNo, productionRecordNumberSubmitParam.getNumber());
        productionRecord.setSpecs(orderItem.getSpecs());
        productionRecord.setSeque(orderItem.getSeque());
        Production production = productionService.findProductionByOrderNoAndSpecs(orderNo, orderItem.getSpecs());
        productionRecord.setProductionId(production.getId());
        productionRecord.setProduction(productionRecordNumberSubmitParam.getProduction().split("-")[0]);
        productionRecord.setStatus(Constant.STATUS_1);
        productionRecord.setNumber(productionRecordNumberSubmitParam.getNumber());
        return productionRecordService.save(productionRecord, productionRecordNumberSubmitParam.getProduction().split("-")[1], false);
    }


    @PostMapping("open/submitUpdate")
    @ApiOperation(value = "修理订单提交工序")
    @Transactional
    public MessageResult submitUpdate(@RequestBody ProductionRecordNumberSubmitParam productionRecordNumberSubmitParam) {
        //  修理订单需要根据规格和工艺去获取符合要求的模具编码

        int success = 0;
        int error = 0;
        String errorMessage = "";
        for (int i = 0; i < productionRecordNumberSubmitParam.getNum(); i++) {
            String ngTag = "0";
            String number = productionRecordService.queryUpdateOrderNumber(productionRecordNumberSubmitParam.getOrderNo(), productionRecordNumberSubmitParam.getSpecs(),
                    productionRecordNumberSubmitParam.getProduction(), ngTag);
            Staff staff = staffService.findByStaffNumber(productionRecordNumberSubmitParam.getStaffNumber());
            if (staff == null) {
                return MessageResult.error("请重新扫码员工码");
            }
            ProductionRecord productionRecord = new ProductionRecord();
            String orderNo = productionRecordNumberSubmitParam.getOrderNo();
            productionRecord.setCreateTime(DateUtil.getFormatedDateTime());
            productionRecord.setOrderNo(orderNo);
            productionRecord.setNgTag(ngTag);
            productionRecord.setStaffId(staff.getId());
            productionRecord.setStaffName(staff.getName());
            productionRecord.setStaffNumber(staff.getNumber());
            OrderItem orderItem = insideOrderService.queryOrderItemByOrderNoAndNumber(orderNo, number);
            productionRecord.setSpecs(orderItem.getSpecs());
            productionRecord.setSeque(orderItem.getSeque());
            productionRecord.setWorkDoneFlag(Constant.WORK_DONE_FLAG_N);
            Production production = productionService.findProductionByOrderNoAndSpecs(orderNo, orderItem.getSpecs());
            productionRecord.setProductionId(production.getId());
            productionRecord.setProduction(productionRecordNumberSubmitParam.getProduction().split("-")[0]);
            productionRecord.setStatus(Constant.STATUS_1);
            productionRecord.setNumber(number);
            MessageResult ms = productionRecordService.save(productionRecord, productionRecordNumberSubmitParam.getProduction().split("-")[1], false);
            if (ms.getCode() == 200) {
                success++;
            } else {
                error++;
                errorMessage = ms.getMessage();
            }
        }
        if (productionRecordNumberSubmitParam.getNgNum() != null) {
            String ngTag = "1";
            for (int i = 0; i < productionRecordNumberSubmitParam.getNgNum(); i++) {
                String number = productionRecordService.queryUpdateOrderNumber(productionRecordNumberSubmitParam.getOrderNo(), productionRecordNumberSubmitParam.getSpecs(),
                        productionRecordNumberSubmitParam.getProduction(), ngTag);
                Staff staff = staffService.findByStaffNumber(productionRecordNumberSubmitParam.getStaffNumber());
                ProductionRecord productionRecord = new ProductionRecord();
                String orderNo = productionRecordNumberSubmitParam.getOrderNo();
                productionRecord.setCreateTime(DateUtil.getFormatedDateTime());
                productionRecord.setOrderNo(orderNo);
                productionRecord.setStaffId(staff.getId());
                productionRecord.setNgTag(ngTag);
                productionRecord.setStaffName(staff.getName());
                productionRecord.setStaffNumber(staff.getNumber());
                OrderItem orderItem = insideOrderService.queryOrderItemByOrderNoAndNumber(orderNo, number);
                productionRecord.setSpecs(orderItem.getSpecs());
                productionRecord.setSeque(orderItem.getSeque());
                productionRecord.setWorkDoneFlag(Constant.WORK_DONE_FLAG_N);
                Production production = productionService.findProductionByOrderNoAndSpecs(orderNo, orderItem.getSpecs());
                productionRecord.setProductionId(production.getId());
                productionRecord.setProduction(productionRecordNumberSubmitParam.getProduction().split("-")[0]);
                productionRecord.setStatus(Constant.STATUS_1);
                productionRecord.setNumber(number);
                MessageResult ms = productionRecordService.save(productionRecord, productionRecordNumberSubmitParam.getProduction().split("-")[1], false);
                if (ms.getCode() == 200) {
                    success++;
                } else {
                    error++;
                    errorMessage = ms.getMessage();
                }
            }
        }


        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        result.put("error", error);
        result.put("errorMessage", errorMessage);
        return MessageResult.getSuccessInstance(result);
    }


    @GetMapping("open/orderProductionRecord")
    @ApiOperation(value = "查询订单的流转信息")
    public MessageResult<List<OrderProductionRecordVo>> orderProductionRecord(String orderNo) {
        List<OrderProductionRecordVo> voList = orderProductionRecordService.queryOrderProductionRecord(orderNo);
        return MessageResult.getSuccessInstance(voList);
    }


    @GetMapping("open/ordersProductionRecord")
    @ApiOperation(value = "查询系统所有流转中订单的流转信息")
    public MessageResult<Map> orderProductionRecord(String orderNo, String type, Integer pageNum, Integer pageSize) {
        //查询系统所有未完成订单
        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 4 : pageSize;
        List<Map> list = new ArrayList<>();
        Page<InsideOrder> orderPage = insideOrderService.findByStatus(Constant.ORDER_STATUS_3, type, orderNo, pageNum, pageSize);
        int nextPageNum = pageNum;
        if (orderPage.getTotalPages() > pageNum) {
            nextPageNum = pageNum + 1;
        } else {
            nextPageNum = 1;
        }
        for (InsideOrder order : orderPage.getContent()) {
            Map<String, Object> m = new HashMap<>();
            m.put("custNo", order.getCustOrderNo());
            List<OrderProductionRecordVo> voList = orderProductionRecordService.queryOrderProductionRecord(order.getOrderNo());
            m.put("list", voList);
            list.add(m);
        }
        Map<String, Object> mapList = new HashMap<>();
        mapList.put("nextPageNum", nextPageNum);
        mapList.put("list", list);
        return MessageResult.getSuccessInstance(mapList);
    }


    @GetMapping("open/subNum")
    @ApiOperation(value = "查询订单的流转信息")
    public MessageResult<Map<String, Object>> subNum(String orderNo, String production) {
        Map<String, Object> map = productionRecordService.subNum(orderNo, production);
        return MessageResult.getSuccessInstance(map);
    }


    @GetMapping("queryOne")
    @ApiOperation(value = "查询某个记录")

    public MessageResult<ProductionRecord> queryOne(String orderNo, String number, String production) {
        ProductionRecord productionRecord = productionRecordService.queryOne(orderNo, number, production);
        return MessageResult.getSuccessInstance(productionRecord);
    }


    @GetMapping("orderItemProductionRecord")
    @ApiOperation(value = "查询订单某个工艺的流转信息")
    public MessageResult<Map<String, Object>> orderProducttoBeTransferredNumionRecord(String orderNo, String
            production, Integer pageNo, Integer pageSize, String number, String specs) {
        Map<String, Object> map = productionRecordService.orderItemProductionRecord(orderNo, production, number, specs, pageNo, pageSize);
        return MessageResult.getSuccessInstance(map);
    }


    @GetMapping("orderItemProductionRecordForUpdate")
    @ApiOperation(value = "查询订单某个工艺的流转信息-修理订单使用")
    public MessageResult<List<Map<String, Object>>> orderItemProductionRecordForUpdate(String orderNo, String
            production) {
        List<Map<String, Object>> voList = productionRecordService.orderItemUpdateProductionRecord(orderNo, production);
        return MessageResult.getSuccessInstance(voList);
    }


    // 退回
    @GetMapping("back")
    @ApiOperation(value = "回退")
    public MessageResult back(String orderNo, String number, String specs, String backProduction) {
        MessageResult mr = productionRecordService.back(orderNo, number, specs, backProduction);
        return mr;
    }


    // 退回
    @GetMapping("open/backList")
    @ApiOperation(value = "批量回退--可回退到多个指定工艺")
    public MessageResult backList(String orderNo, String number, String specs, String backProduction) {
        List<String> list = StringUtil.stringToList(number, ",");
        for (String s : list) {
            productionRecordService.back(orderNo, s, specs, backProduction);
        }
        return MessageResult.success();
    }

    @GetMapping("open/backForUpdate")
    @ApiOperation(value = "修理品回退 只能默认回退到上一工艺 backProduction 为空")
    public MessageResult backForUpdate(String orderNo, Integer num, String staffName, String specs, String nowProduction, String
            backProduction) {
        // 通过 orderNo  specs  staffName 查找复合要求的number
        if (num == null || num == 0) {
            return MessageResult.error("请输入回退数量");
        }
        List<String> numbers = productionRecordService.queryBackNumber(orderNo, specs, staffName, nowProduction, num);
        for (String number : numbers) {
            MessageResult mr = productionRecordService.back(orderNo, number, specs, backProduction);
            System.out.println("回退结果：" + mr.getMessage());
        }
        return MessageResult.success();
    }

    // 查询可回退数量
    @GetMapping("open/backForUpdateNum")
    @ApiOperation(value = "修理品回退数量")
    public MessageResult backForUpdateNum(String orderNo, String staffName, String specs, String nowProduction) {
        List<String> numbers = productionRecordService.queryBackNumber(orderNo, specs, staffName, nowProduction, Integer.MAX_VALUE);
        return MessageResult.getSuccessInstance((Object) numbers.size());
    }


    //查询某个产品的流转详情
    @GetMapping("orderItemProductionInfo")
    @ApiOperation(value = "查询订单某个产品的流转信息")
    public MessageResult<List<OrderProductionRecordVo>> orderItemProductionInfo(String orderNo, String
            number, String specs) {
        List<OrderProductionRecordVo> voList = productionRecordService.queryOrderItemProductionRecord(orderNo, number, specs);
        return MessageResult.getSuccessInstance(voList);
    }


    @GetMapping("open/productionsWithTag")
    @ApiOperation(value = "查询订单某个产品的流转列表,包含开始-结束")
    public MessageResult<List<String>> productionsWithTag(String orderNo, String specs) {
        List<String> list = productionService.productions(orderNo, specs);
        List<String> result = new ArrayList<>();
        for (String s : list) {
            result.add(s + "-" + Constant.PRODUCTION_RECORD_TAG_START);
            result.add(s + "-" + Constant.PRODUCTION_RECORD_TAG_END);
        }
        return MessageResult.getSuccessInstance(result);
    }


    @GetMapping("/open/productions")
    @ApiOperation(value = "查询订单某个产品的流转列表")
    public MessageResult<List<String>> productions(String orderNo, String specs) {
        List<String> list = productionService.productions(orderNo, specs);
        return MessageResult.getSuccessInstance(list);
    }

    /**
     * 根据订单和规格  查询 某个工艺流程待流转的数量
     */
    @GetMapping("open/toBeTransferredNum")
    @ApiOperation(value = "查询可流转数量")
    public MessageResult<Map> toBeTransferredNum(String orderNo, String specs, String production) {
        Map num = productionRecordService.toBeTransferredNum(orderNo, specs, production);
        return MessageResult.getSuccessInstance(num);
    }

}
